package com.useeinfo.asg.open.admin;

import com.useeinfo.asg.common.utils.CommUtil;
import com.useeinfo.asg.modules.logging.biz.ProjectBiz;
import com.useeinfo.asg.modules.logging.biz.VersionBiz;
import com.useeinfo.asg.modules.logging.entity.Project;
import com.useeinfo.asg.modules.logging.entity.Version;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.xiaoleilu.hutool.util.CollectionUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created by THINK on 2017/4/27.
 */
@Controller
@RequestMapping("/admin/version")
public class VersionAdminManageAction {

    @Autowired
    private VersionBiz versionBiz;
    @Autowired
    private ProjectBiz projectBiz;

    @RequestMapping("/list")
    public String list(HttpServletRequest request, ModelMap mv) {

        mv.put("projId", request.getParameter("projId"));
        return "/admin/version/list";
    }

    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJosn(HttpServletRequest request,
                               @RequestParam(value = "page", required = false) String pageNowParam,
                               @RequestParam(value = "rows", required = false) String pageSizeParam,
                               @RequestParam(value = "sidx", required = false) String sidxParam,
                               @RequestParam(value = "sord", required = false) String sordParam) {

        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        String projId = CommUtil.null2String(request.getParameter("projId"));
        if (!projId.trim().equals("")) {
            queryParam.getSqlMap().put("projId", projId);
        }else {
            queryParam.getSqlMap().put("id", "0");
        }
        if(!CommUtil.null2String(sidxParam).equals("") && !CommUtil.null2String(sordParam).equals("") ) {
            queryParam.setSqlOrder("order by s." + sidxParam + " " + sordParam);
        }
        return versionBiz.findJSONList(queryParam);
    }

    @RequestMapping("/addOrEdit")
    @ResponseBody
    public JSONObject add(HttpServletRequest request) {

        JSONObject retJson = CommUtil.jsonResult(false);
        try {
            long id = CommUtil.null2Long(request.getParameter("id"));
            long projId = CommUtil.null2Long(request.getParameter("projId"));
            Project project = projectBiz.findModel(projId);
            String versionNum = CommUtil.null2String(request.getParameter("version"));
            String publishTimeStr = CommUtil.null2String(request.getParameter("publishTime"));
            Object c = request.getParameter("contents");
            String content = CommUtil.null2String(request.getParameter("contents"));
            Date publishTime = publishTimeStr.equals("") ? null : CommUtil.parseShortDate(publishTimeStr);
            Version version = null;
            if (id <= 0 || (version = versionBiz.findModel(id)) == null) {
                version = new Version();
                version.setCreateTime(new Date());
                version.setProject(project);
            }
            version.setVersion(versionNum);
            version.setPublishTime(publishTime);
            version.setContent(content);
            versionBiz.addOrUpdate(version);

            // 判断是否是当前版本或者计划版本
            if(version.isCurrVersion()) {
                project.setCurrentVersion(version.getVersion());
                project.setPublishTime(version.getPublishTime());
                projectBiz.update(project);
            }
            if(version.isNextVersion()) {
                project.setNextVersion(version.getVersion());
                project.setNextPublishTime(version.getPublishTime());
                projectBiz.update(project);
            }
            retJson = CommUtil.jsonResult(true);
        }
        catch (Exception e) {
            retJson.put("msg", "保存/修改记录时发生错误");
        }
        return retJson;
    }

    /**
     * 获得编辑页面
     * @param request
     * @param mv
     * @return
     */
    @RequestMapping(value = "/editPage", produces = "text/html;charset=UTF-8")
    public String edit(HttpServletRequest request, ModelMap mv) {

        long id = CommUtil.null2Long(request.getParameter("id"));
        long projId = CommUtil.null2Long(request.getParameter("projectId"));
        Version version = null;
        if (id > 0 && (version = versionBiz.findModel(id)) != null) {
            mv.put("version", version);
        }
        mv.put("projId", projId);
        return "/admin/version/edit";
    }

    /**
     * 设置当前版本
     * @param request
     * @return
     */
    @RequestMapping(value = "/setCurrVersion")
    @ResponseBody
    public JSONObject setCurrVersion(HttpServletRequest request) {

        JSONObject retJson = CommUtil.jsonResult(false);
        long id = CommUtil.null2Long(request.getParameter("id"));
        long projId = CommUtil.null2Long(request.getParameter("projectId"));

        Version version;
        Project project;
        if(id > 0 && (version = versionBiz.findModel(id)) != null) {
            if(projId > 0 && (project = projectBiz.findModel(projId)) != null) {
                if(version.getProject() != null && project.getId() == version.getProject().getId()) {
                    // 处理版本数据
                    QueryParam queryParam = new QueryParam(-1, -1);
                    queryParam.getSqlMap().put("projId", CommUtil.null2String(projId));
                    queryParam.getSqlMap().put("currVersion", CommUtil.null2String(true));
                    List<Version> versionList = versionBiz.findList(queryParam);
                    if(CollectionUtil.isNotEmpty(versionList)) {
                        for(Version tmpVersion : versionList) {
                            tmpVersion.setCurrVersion(false);
                            versionBiz.update(tmpVersion);
                        }
                    }

                    version.setCurrVersion(true);
                    versionBiz.update(version);

                    // 处理项目信息
                    project.setCurrentVersion(version.getVersion());
                    project.setPublishTime(version.getPublishTime());
                    projectBiz.update(project);
                    retJson = CommUtil.jsonResult(true);
                }else {
                    retJson.put("msg", "项目数据与版本数据不匹配");
                }
            }else {
                retJson.put("msg", "未找到项目数据");
            }
        }else {
            retJson.put("msg", "未找到版本数据");
        }

        return retJson;
    }

    /**
     * 设置计划版本
     * @param request
     * @return
     */
    @RequestMapping(value = "/setNextVersion")
    @ResponseBody
    public JSONObject setNextVersion(HttpServletRequest request) {

        JSONObject retJson = CommUtil.jsonResult(false);
        long id = CommUtil.null2Long(request.getParameter("id"));
        long projId = CommUtil.null2Long(request.getParameter("projectId"));

        Version version;
        Project project;
        if(id > 0 && (version = versionBiz.findModel(id)) != null) {
            if(projId > 0 && (project = projectBiz.findModel(projId)) != null) {
                if(version.getProject() != null && project.getId() == version.getProject().getId()) {
                    // 处理版本数据
                    QueryParam queryParam = new QueryParam(-1, -1);
                    queryParam.getSqlMap().put("projId", CommUtil.null2String(projId));
                    queryParam.getSqlMap().put("nextVersion", CommUtil.null2String(true));
                    List<Version> versionList = versionBiz.findList(queryParam);
                    if(CollectionUtil.isNotEmpty(versionList)) {
                        for(Version tmpVersion : versionList) {
                            tmpVersion.setNextVersion(false);
                            versionBiz.update(tmpVersion);
                        }
                    }

                    version.setNextVersion(true);
                    versionBiz.update(version);

                    // 处理项目信息
                    project.setNextVersion(version.getVersion());
                    project.setNextPublishTime(version.getPublishTime());
                    projectBiz.update(project);
                    retJson = CommUtil.jsonResult(true);
                }else {
                    retJson.put("msg", "项目数据与版本数据不匹配");
                }
            }else {
                retJson.put("msg", "未找到项目数据");
            }
        }else {
            retJson.put("msg", "未找到版本数据");
        }

        return retJson;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public JSONObject delete(HttpServletRequest request, ModelMap mv) {

        JSONObject retJson = CommUtil.jsonResult(false);
        try {
            long id = CommUtil.null2Long(request.getParameter("id"));
            Version version = null;
            if (id > 0 && (version = versionBiz.findModel(id)) != null) {
                version.setDeleteStatus(true);
                versionBiz.update(version);

                Project project;
                if(version.isCurrVersion()) {
                    project = version.getProject();
                    project.setCurrentVersion("");
                    project.setPublishTime(null);
                    projectBiz.update(project);
                }
                if(version.isNextVersion()) {
                    project = version.getProject();
                    project.setNextVersion("");
                    project.setNextPublishTime(null);
                    projectBiz.update(project);
                }
                retJson = CommUtil.jsonResult(true);
            }else {
                retJson.put("msg", "未找到相应记录");
            }
        }
        catch (Exception e) {
            retJson.put("msg", "删除记录时发生错误");
        }
        return retJson;
    }
}
